package com.snail.snailvr.disk.dropbox;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.TextView;

import com.dropbox.core.DbxException;
import com.dropbox.core.android.Auth;
import com.dropbox.core.v2.files.FileMetadata;
import com.dropbox.core.v2.files.FolderMetadata;
import com.dropbox.core.v2.files.ListFolderResult;
import com.dropbox.core.v2.users.FullAccount;
import com.snail.snailvr.R;
import com.snail.snailvr.event.BusProvider;
import com.snail.snailvr.event.OauthSuccessEvent;
import com.snail.snailvr.model.InputItem;
import com.snail.snailvr.utils.DatabaseUtils;
import com.snail.snailvr.utils.LogUtils;
import com.snail.snailvr.utils.SharedPreferencesUtil;
import com.snail.snailvr.utils.ToastUtils;
import com.snail.snailvr.views.BaseToolbarActivity;
import com.snail.snailvr.widget.WrapContentLinearLayoutManager;
import com.squareup.otto.Subscribe;

import java.io.File;
import java.text.DateFormat;
import java.util.List;

import butterknife.Bind;
import rx.Single;
import rx.SingleSubscriber;
import rx.schedulers.Schedulers;

/**
 * Activity that displays the content of a path in dropbox and lets users navigate folders,
 * and upload/download files
 */
public class FilesActivity extends BaseToolbarActivity {
    private static final String TAG = FilesActivity.class.getName();

    public final static String EXTRA_PATH = "FilesActivity_Path";
    public final static String FOLDER_NAME = "folder_name";

    public final static int FINISH_ALL = 1000;
    public final static int KEEP = 2000;

    private String mPath="";

    private String current_folder_name;

    private FilesAdapter mFilesAdapter;

    private FileMetadata mSelectedFile;

    private SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.toolbar)
    public Toolbar mToolbar;
    @Bind(R.id.files_list)
    RecyclerView recyclerView;

    @Bind(R.id.log_out)
    TextView log_out;

    @Bind(R.id.account_name)
    TextView account_name;

    @Bind(R.id.loading)
    View loading;

    @Bind(R.id.no_data)
    View no_data;

    private boolean isOauthReturned=false;

    public static Intent getIntent(Context context, String path, String folderName) {
        Intent filesIntent = new Intent(context, FilesActivity.class);
        filesIntent.putExtra(FilesActivity.EXTRA_PATH, path);
        filesIntent.putExtra(FilesActivity.FOLDER_NAME, folderName);
        return filesIntent;
    }

    @Override
    protected void handleIntent() {
        String path = getIntent().getStringExtra(EXTRA_PATH);
        mPath = path == null ? "" : path;
        LogUtils.d("file path=" + mPath);
        current_folder_name = getIntent().getStringExtra(FOLDER_NAME);
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        BusProvider.getInstance().unregister(this);
    }

    @Override
    protected void initView() {
        BusProvider.getInstance().register(this);

        setupToolbar(mToolbar, current_folder_name, -1);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setResult(KEEP);
                finish();
            }
        });

        String token=SharedPreferencesUtil.getInstance(this).getDropboxToken();
        if (token!=null) {
            initAndLoadData(token);
            initUi();
        }else{
            Auth.startOAuth2Authentication(this, getString(R.string.app_key));
        }

        log_out.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferencesUtil.getInstance(FilesActivity.this).removeDropboxToken();
                DatabaseUtils.saveDisconnectedInputItem(getResources().getString(R.string.connect_to_dropbox_account), getResources().getString(R.string.dropBox));
                setResult(FINISH_ALL);
                finish();
            }
        });
    }

    private String getToken() {
        return SharedPreferencesUtil.getInstance(this).getDropboxToken();

    }

    private void initUi() {

        recyclerView = (RecyclerView) findViewById(R.id.files_list);
        mFilesAdapter = new FilesAdapter(new FilesAdapter.Callback() {

            @Override
            public void onFolderClicked(FolderMetadata folder) {
                startActivityForResult(FilesActivity.getIntent(FilesActivity.this, folder.getPathLower(), folder.getName()), 0);
            }

            @Override
            public void onFileClicked(final FileMetadata file) {
                mSelectedFile = file;
                performWithPermissions(FileAction.DOWNLOAD);
            }
        });
        recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(this));
        recyclerView.setAdapter(mFilesAdapter);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadDropboxData();
            }
        });
        swipeRefreshLayout.setVisibility(View.GONE);
        swipeRefreshLayout.setColorSchemeResources(R.color.positive_normal_color);

        no_data.setVisibility(View.GONE);

        mSelectedFile = null;

        DatabaseUtils.getConnectedNetDiskAccountName(getResources().getString(R.string.dropBox), new SingleSubscriber() {
            @Override
            public void onSuccess(Object value) {
                account_name.setText((String) value);
            }

            @Override
            public void onError(Throwable error) {
                // do nothing
            }
        });
    }

    @Subscribe
    public void onOauthSuccess(OauthSuccessEvent event){
        DatabaseUtils.getConnectedNetDiskAccountName(getResources().getString(R.string.dropBox), new SingleSubscriber() {
            @Override
            public void onSuccess(Object value) {
                account_name.setText((String) value);
            }

            @Override
            public void onError(Throwable error) {

            }
        });
    }

    @Override
    protected void loadData() {
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.dropbox_activity_files;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == FINISH_ALL) {
            setResult(resultCode);
            finish();
        }
        else {
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        String accessToken = getToken();

        if (accessToken == null) {
            accessToken = Auth.getOAuth2Token();

            if (accessToken != null) {
                SharedPreferencesUtil.getInstance(this).saveDropboxToken(accessToken);
                initAndLoadData(accessToken);
                getAccountInfo();
                initUi();
            } else {
                showAuthHint();
            }
        }
    }

    private void initAndLoadData(String accessToken) {
        DropboxClientFactory.init(accessToken);

        // PicassoClient.init(getApplicationContext(), DropboxClientFactory.getClient());

        loadDropboxData();
    }

    /**
     * 获取dropbox的账号信息
     */
    private void getAccountInfo() {
        Single.create(new Single.OnSubscribe<FullAccount>() {
            @Override
            public void call(SingleSubscriber<? super FullAccount> singleSubscriber) {
                try {
                    FullAccount account=DropboxClientFactory.getClient().users().getCurrentAccount();
                    singleSubscriber.onSuccess(account);
                } catch (DbxException e) {
                    LogUtils.d("DbxException="+e.toString());
                }

            }
        }).subscribeOn(Schedulers.io()).subscribe(new SingleSubscriber<FullAccount>() {
            @Override
            public void onSuccess(FullAccount account) {
                if (account != null) {
                    // 保存登录数据到数据库
                    InputItem item = new InputItem(account.getEmail(), getString(R.string.dropBox));
                    DatabaseUtils.saveConnectedInputItem(item);
                }
            }

            @Override
            public void onError(Throwable error) {
                LogUtils.d("error=" + error.toString());
            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int actionCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        FileAction action = FileAction.fromCode(actionCode);

        boolean granted = true;
        for (int i = 0; i < grantResults.length; ++i) {
            if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                Log.w(TAG, "User denied " + permissions[i] +
                        " permission to perform file action: " + action);
                granted = false;
                break;
            }
        }

        if (granted) {
            performAction(action);
        } else {
            switch (action) {
                case UPLOAD:
                    ToastUtils.showToast("Can't upload file: read access denied. " + "Please grant storage permissions to use this functionality.");
                    break;
                case DOWNLOAD:
                    ToastUtils.showToast("Can't download file: write access denied. " + "Please grant storage permissions to use this functionality.");
                    break;
            }
        }
    }

    private void performAction(FileAction action) {
        switch (action) {
            case DOWNLOAD:
                if (mSelectedFile != null) {
                    downloadFile(mSelectedFile);
                } else {
                    Log.e(TAG, "No file selected to download.");
                }
                break;
            default:
                Log.e(TAG, "Can't perform unhandled file action: " + action);
        }
    }

    protected void loadDropboxData() {

        new ListFolderTask(DropboxClientFactory.getClient(), new ListFolderTask.Callback() {

            @Override
            public void onDataLoaded(ListFolderResult result) {

                mFilesAdapter.setFiles(result.getEntries());

                swipeRefreshLayout.setRefreshing(false);

                loading.setVisibility(View.GONE);

                // 过滤后 存在有效数据
                if(mFilesAdapter.getmFiles().size() > 0){

                    swipeRefreshLayout.setVisibility(View.VISIBLE);

                    no_data.setVisibility(View.GONE);
                }
                else{// 不存在

                    swipeRefreshLayout.setVisibility(View.GONE);

                    no_data.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(Exception e) {

                ToastUtils.makeToastColorShow(FilesActivity.this, swipeRefreshLayout, getResources().getString(R.string.error_occurred));

                swipeRefreshLayout.setRefreshing(false);

                // 出错下 处理各种视图
                loading.setVisibility(View.GONE);

                no_data.setVisibility(View.GONE);
                swipeRefreshLayout.setVisibility(View.VISIBLE);

            }
        }).execute(mPath);
    }

    protected void showAuthHint() {
        if(isOauthReturned) {
            ToastUtils.makeToastColorShow(FilesActivity.this,swipeRefreshLayout,getString(R.string.oauth_fail));
            finish();
        }
        isOauthReturned=true;
    }

    private void downloadFile(FileMetadata file) {
        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setCancelable(false);
        dialog.setMessage(getString(R.string.downloading));
        dialog.show();

        new DownloadFileTask(FilesActivity.this, DropboxClientFactory.getClient(), new DownloadFileTask.Callback() {
            @Override
            public void onDownloadComplete(File result) {
                dialog.dismiss();

                if (result != null) {
                    viewFileInExternalApp(result);
                }
            }

            @Override
            public void onError(Exception e) {
                dialog.dismiss();

                Log.e(TAG, "Failed to download file.", e);
                ToastUtils.makeToastColorShow(FilesActivity.this, swipeRefreshLayout, getString(R.string.error_occurred));
            }
        }, "").execute(file);

    }

    private void viewFileInExternalApp(File result) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        String ext = result.getName().substring(result.getName().indexOf(".") + 1);
        String type = mime.getMimeTypeFromExtension(ext);

        intent.setDataAndType(Uri.fromFile(result), type);

        // Check for a handler first to avoid a crash
        PackageManager manager = getPackageManager();
        List<ResolveInfo> resolveInfo = manager.queryIntentActivities(intent, 0);
        if (resolveInfo.size() > 0) {
            startActivity(intent);
        }
    }

    private void uploadFile(String fileUri) {
        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setCancelable(false);
        dialog.setMessage("Uploading");
        dialog.show();

        new UploadFileTask(this, DropboxClientFactory.getClient(), new UploadFileTask.Callback() {
            @Override
            public void onUploadComplete(FileMetadata result) {
                dialog.dismiss();

                String message = result.getName() + " size " + result.getSize() + " modified " +
                        DateFormat.getDateTimeInstance().format(result.getClientModified());
                ToastUtils.showToast(message);

                // Reload the folder
                loadData();
            }

            @Override
            public void onError(Exception e) {
                dialog.dismiss();

                Log.e(TAG, "Failed to upload file.", e);
                ToastUtils.showToast(R.string.error_occurred);
            }
        }).execute(fileUri, mPath);
    }

    private void performWithPermissions(final FileAction action) {
        if (hasPermissionsForAction(action)) {
            performAction(action);
            return;
        }

        if (shouldDisplayRationaleForAction(action)) {
            new AlertDialog.Builder(this)
                    .setMessage("This app requires storage access to download and upload files.")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            requestPermissionsForAction(action);
                        }
                    })
                    .setNegativeButton("Cancel", null)
                    .create()
                    .show();
        } else {
            requestPermissionsForAction(action);
        }
    }

    private boolean hasPermissionsForAction(FileAction action) {
        for (String permission : action.getPermissions()) {
            int result = ContextCompat.checkSelfPermission(this, permission);
            if (result == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    private boolean shouldDisplayRationaleForAction(FileAction action) {
        for (String permission : action.getPermissions()) {
            if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                return true;
            }
        }
        return false;
    }

    private void requestPermissionsForAction(FileAction action) {
        ActivityCompat.requestPermissions(
                this,
                action.getPermissions(),
                action.getCode()
        );
    }

    @Override
    protected boolean onToolbarMenuItemClick(MenuItem item) {
        return false;
    }

    private enum FileAction {

        DOWNLOAD(Manifest.permission.WRITE_EXTERNAL_STORAGE),
        UPLOAD(Manifest.permission.READ_EXTERNAL_STORAGE);

        private static final FileAction[] values = values();

        private final String[] permissions;

        FileAction(String... permissions) {
            this.permissions = permissions;
        }

        public int getCode() {
            return ordinal();
        }

        public String[] getPermissions() {
            return permissions;
        }

        public static FileAction fromCode(int code) {
            if (code < 0 || code >= values.length) {
                throw new IllegalArgumentException("Invalid FileAction code: " + code);
            }
            return values[code];
        }
    }
}
